package cn.net.autocode.platform.file.service;

import cn.net.autocode.dbManager.IdWorker;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class FileHandle {

    public static byte[] readFile(String rootDir,String path){
        String filePath = rootDir+path;
        try {
            // 一行代码读取：Paths.get() 转换路径，Files.readAllBytes() 读取字节数组
            byte[] fileBytes = Files.readAllBytes(Paths.get(filePath));
            return fileBytes;
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    public static boolean deleteFromDisk(String rootDir,String path) throws IOException {

        String filePath = rootDir+path;
        System.out.println(filePath);

        Path fileToDelete = Paths.get(filePath);

        // 2. 检查文件是否存在
        if (!Files.exists(fileToDelete)) {
            return false;
        }

        // 3. 检查是否为文件（避免误删目录）
        if (!Files.isRegularFile(fileToDelete)) {
            throw new IllegalArgumentException("路径不是文件：" + filePath);
        }

        // 4. 执行删除（删除失败会抛出 IOException，含详细原因）
        Files.delete(fileToDelete);
        return true;
    }

    public static JSONObject saveToUploadDisk(String rootDir,MultipartFile file) throws IOException {
        //获取月份信息
        LocalDate localDate = LocalDate.now();
        String yyyyMM = localDate.format(DateTimeFormatter.ofPattern("yyyyMM"));

        String uploadPath = rootDir+"/upload/"+yyyyMM;

        File dir = new File(uploadPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        String originalFilename = file.getOriginalFilename(); // 原文件名（如 "test.jpg"）
        String fileSuffix = getFileSuffix(originalFilename); // 获取文件后缀（如 .jpg）
        String fileId = IdWorker.ulid();
        String uniqueFilename = fileId + "." +fileSuffix; // 唯一文件名

        JSONObject fj = new JSONObject();
        fj.put("filePath","/upload/"+yyyyMM+"/"+uniqueFilename);
        fj.put("fileId",fileId);
        fj.put("fileType",fileSuffix);
        fj.put("fileName",originalFilename);

        BigDecimal primitiveSize = new BigDecimal(file.getBytes().length);
        BigDecimal divisor = new BigDecimal(1024);
        BigDecimal fileSize = primitiveSize.divide(divisor, 2, RoundingMode.HALF_UP);
        fj.put("fileSize",fileSize);

        // 4. 构建目标文件路径（目录 + 唯一文件名）
        File targetFile = new File(dir, uniqueFilename);

        // 5. 存储文件（核心方法：transferTo，自动处理流的打开/关闭）
        file.transferTo(targetFile);
        return fj;
    }

    public static String[] moveToUploadDisk(String rootDir,String source) throws IOException {

        //获取月份信息
        LocalDate localDate = LocalDate.now();
        String yyyyMM = localDate.format(DateTimeFormatter.ofPattern("yyyyMM"));

        String uploadPath = rootDir+"/upload/"+yyyyMM;

        File dir = new File(uploadPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        Path sourcePath = Paths.get(rootDir+source);

        Path targetPath = Paths.get(uploadPath+"/"+sourcePath.getFileName());

        // 核心：剪贴文件（move = 移动/复制+删除）
        Files.move(
                sourcePath,
                targetPath,
                StandardCopyOption.REPLACE_EXISTING, // 目标文件已存在则覆盖
                StandardCopyOption.ATOMIC_MOVE       // 同一文件系统下原子操作（保证完整性）
        );

        return new String[]{"/upload/"+yyyyMM+"/"+sourcePath.getFileName()};
    }


    public static JSONObject saveToTempDisk(String rootDir,MultipartFile file) throws IOException {

        String uploadPath = rootDir+"/tempFile";
        System.out.println(uploadPath);
        File dir = new File(uploadPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        String originalFilename = file.getOriginalFilename(); // 原文件名（如 "test.jpg"）
        String fileSuffix = getFileSuffix(originalFilename); // 获取文件后缀（如 .jpg）
        String fileId = IdWorker.ulid();
        String uniqueFilename = fileId + "." +fileSuffix; // 唯一文件名

        //记录附件信息
        JSONObject fj = new JSONObject();
        fj.put("filePath","/tempFile/"+uniqueFilename);
        fj.put("fileId",fileId);
        fj.put("fileType",fileSuffix);
        fj.put("fileName",originalFilename);

        BigDecimal primitiveSize = new BigDecimal(file.getBytes().length);
        BigDecimal divisor = new BigDecimal(1024);
        BigDecimal fileSize = primitiveSize.divide(divisor, 2, RoundingMode.HALF_UP);
        fj.put("fileSize",fileSize);

        // 4. 构建目标文件路径（目录 + 唯一文件名）
        File targetFile = new File(dir, uniqueFilename);

        // 5. 存储文件（核心方法：transferTo，自动处理流的打开/关闭）
        file.transferTo(targetFile);


        return fj;
    }

    public static String getFileSuffix(String originalFilename) {
        if (originalFilename == null || originalFilename.lastIndexOf(".") == -1) {
            return ""; // 无后缀文件（如 "README"）
        }
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        if (suffix.length() > 1) {
            suffix = suffix.substring(1);
            return suffix.toLowerCase();
        }else{
            return "";
        }
    }
}
